package top.eleven.sixpence.generaterollbacksql.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.eleven.sixpence.generaterollbacksql.common.CommonConstant;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;

/**
 * 文件工具类，用于将结果保存至磁盘文件中
 *
 * @author eleven
 */
public class FileUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 将数据写入文件保存至磁盘中
     *
     * @param data 保存的数据
     * @param outputPath 保存数据的文件夹路径
     * @param fileName 文件名
     */
    public static void outputFile(String data, String outputPath, String fileName) {
        File outputFile = new File(outputPath + File.separator + fileName);
        try (RandomAccessFile writer = new RandomAccessFile(outputFile, "rws")){
            //写入前锁定文件，防止其他程序同时操作文件导致错误
            FileLock fl = writer.getChannel().tryLock();
            if (fl.isValid()) {
                long length = outputFile.length();
                writer.seek(length);
                if(length > 0 ) {
                    writer.write(CommonConstant.NEW_LINE.getBytes(CommonConstant.ENCODING_UTF8));
                }
                writer.write(data.getBytes(CommonConstant.ENCODING_UTF8));
                fl.release();
            }
        } catch (Exception e) {
            LOGGER.error("write data to file filed!");
            printData2Console(data);
        }
    }

    private static void printData2Console(String data) {
        LOGGER.error("==========================data===========================");
        LOGGER.error(data);
        LOGGER.error("=========================================================");
    }

}
